package com.kangyi.admin.service.Impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kangyi.admin.mapper.AdminUserMapper;
import com.kangyi.admin.mapper.FeedbackMapper;
import com.kangyi.admin.service.FeedbackService;
import com.kangyi.constant.MessageConstant;
import com.kangyi.context.BaseContext;
import com.kangyi.dto.FeedbackPageQueryDTO;
import com.kangyi.dto.ReplyFeedbackDTO;
import com.kangyi.entity.UserComplaint;
import com.kangyi.exception.DataNotExistException;
import com.kangyi.exception.PermissionsException;
import com.kangyi.result.FeedbackPageResult;
import com.kangyi.vo.AdminUserVO;
import com.kangyi.vo.FeedbackDetailVO;
import com.kangyi.vo.FeedbackPageQueryVO;
import com.kangyi.vo.UserComplaintImgVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.List;


/**
 * @author Blank
 * @version 1.0
 */
@Service
public class FeedbackServiceImpl implements FeedbackService {

    @Autowired
    private FeedbackMapper feedbackMapper;

    @Autowired
    private AdminUserMapper adminUserMapper;

    //调用后检查当前线程id是否有足够的权限进行后续操作
    public void validateUserPermissions() {
        Integer currentId = BaseContext.getCurrentId();
        AdminUserVO adminUserVO = adminUserMapper.selectById(currentId);
        if (!adminUserVO.getPermissions().equals(1)) {
            throw new PermissionsException(MessageConstant.INSUFFICIENT_PRIVILEGE);
        }
    }

    @Override
    public FeedbackPageResult pageQuery(FeedbackPageQueryDTO feedbackPageQueryDTO) {
        validateUserPermissions();
        PageHelper.startPage(feedbackPageQueryDTO.getPage(),feedbackPageQueryDTO.getPageSize());
        Page<FeedbackPageQueryVO> page = feedbackMapper.pageQuery(feedbackPageQueryDTO);
        long total = page.getTotal();
        List<FeedbackPageQueryVO> result = page.getResult();
        if (CollUtil.isEmpty(result)) {
            throw new DataNotExistException(MessageConstant.DATA_NOT_EXIST);
        }

        int pending = 0;
        int inProgress = 0;
        int alreadyProcessed = 0;

        for (FeedbackPageQueryVO vo : result) {
            if (vo.getStatus() == 0) {
                pending++;
            } else if (vo.getStatus() == 1) {
                inProgress++;
            } else if (vo.getStatus() == 2) {
                alreadyProcessed++;
            }
        }
        return new FeedbackPageResult(total,result,pending,inProgress,alreadyProcessed);
    }

    @Override
    @Transactional
    public void deleteFeedback(List<Integer> feedbackIds) {
        validateUserPermissions();
        feedbackMapper.deleteFeedbackImages(feedbackIds);
        feedbackMapper.deleteFeedback(feedbackIds);
    }

    @Override
    public FeedbackDetailVO detailFeedback(Integer feedbackId) {
        validateUserPermissions();
        FeedbackDetailVO feedbackDetailVO = feedbackMapper.detailFeedback(feedbackId);
        if (feedbackDetailVO == null) {
            throw new DataNotExistException(MessageConstant.DATA_NOT_EXIST);
        }
        List<UserComplaintImgVO> userComplaintImgVOList = feedbackMapper.getByFeedbackId(feedbackId);
        feedbackDetailVO.setUserComplaintImgVOList(userComplaintImgVOList);
        feedbackDetailVO.setIsReply(feedbackDetailVO.getReply() != null);
        return feedbackDetailVO;
    }

    @Override
    public void replyFeedback(ReplyFeedbackDTO replyFeedbackDTO) {
        validateUserPermissions();
        if (isNullOrEmpty(replyFeedbackDTO.getReply()) || replyFeedbackDTO.getStatus() == null) {
            throw new DataNotExistException(MessageConstant.DATA_LACK);
        }

        if (!isValidStatus(replyFeedbackDTO.getStatus())) {
            throw new DataNotExistException(MessageConstant.INVALID_STATE_VALUE + replyFeedbackDTO.getStatus());
        }

        UserComplaint build = UserComplaint.builder()
                .id(replyFeedbackDTO.getId())
                .reply(replyFeedbackDTO.getReply())
                .status(replyFeedbackDTO.getStatus())
                .replyTime(LocalDateTime.now())
                .build();
        feedbackMapper.replyFeedback(build);
    }

    private boolean isNullOrEmpty(String str) {
        return str == null || str.trim().isEmpty();
    }

    private boolean isValidStatus(Integer status) {
        // 假设合法状态值为 1、2、3
        return status != null && (status == 1 || status == 2 || status == 3);
    }
}
